package com.atgugui.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atgugui.gulimall.search.config.GulimallElasticsearchConfig;
import com.atgugui.gulimall.search.constant.EsConstant;
import com.atgugui.gulimall.search.service.ProductSaveService;
import com.atguigu.common.to.es.SkuEsModel;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {
    @Resource
    RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModelList) throws IOException {
        //保存到es中
        //1、给es建立索引。product, 在kbana中建立好
        //2、给es保存这些信息

        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel esModel : skuEsModelList) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(esModel.getSkuId().toString());
            indexRequest.source(JSON.toJSONString(esModel), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        //BulkRequest bulkRequest, RequestOptions options
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticsearchConfig.COMMON_OPTIONS);

        //TODO 1、如果有错误记录日志
        boolean b = bulk.hasFailures();
        BulkItemResponse[] items = bulk.getItems();
        List<String> collect = Arrays.stream(items).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.info("商品上架完成：{}, 数据：{}", collect, bulk);

        return b;
    }
}
